package com.acme.bankapp.domain.bank;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.ClientRegistrationListener;

public class Bank implements Serializable {
	private static final long serialVersionUID = -2840885510330537029L;
	
	static final String MES_CLIENT_EXIST = "Client with given name already exists";
		
	private Set<Client> clients = new HashSet<>();
	
	private List<ClientRegistrationListener> listeners = new ArrayList<>();
	
	public class PrintClientListener implements ClientRegistrationListener {
		private static final long serialVersionUID = -9001445264960729318L;

		public void onClientAdded(Client c) {
			System.out.println("Client <" + c.getClientSalutation() + "> added");
		}
	}
	
	public Bank() {
		
		// DebugListener
		addListener( new ClientRegistrationListener() {
			private static final long serialVersionUID = -1284050215137377340L;

			public void onClientAdded(Client c) {
				System.out.println(new Date().toString() + ": Client<" + c.getClientSalutation() + "> added");
			}
		});
	}
		
	public Set<Client> getClients() {
		return Collections.unmodifiableSet(clients);
	}
	
	public void addClient(Client client) throws ClientExistsException {
				
		if (checkClientExist(client)) {
			throw new ClientExistsException(MES_CLIENT_EXIST, client.getClientSalutation());
		}
		
		clients.add(client);
		
		for (ClientRegistrationListener listener : listeners) {
			listener.onClientAdded(client);
		}
	}
	
	private boolean checkClientExist(Client client) {
		return clients.contains(client);
	}

	public void addListener(ClientRegistrationListener listener) {
		listeners.add(listener);	
	}
}
